package com.tr.rentcar.controller.loginandregister;

import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tr.rentcar.common.VerifyCodeUtils;

/**
 * Servlet implementation class CaptchaController
 */
@WebServlet("/yzm")
public class CaptchaController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String CAPTCHA_KEY = "session_captcha";

	private Random rnd = new Random();   
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		// 生成随机字串
		String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
				
		// 生成图片
		int w = 100, h = 32;
		VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

		// 将验证码存储在session以便登录时校验
		request.getSession().setAttribute(CAPTCHA_KEY, verifyCode.toLowerCase());
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
